System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

62% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design an Ad Click Aggregator
Image

Here is the step-by-step system design for an Ad Click Aggregator.

1. Problem Definition and Scope

We are designing a backend system to track, process, and count user clicks on digital advertisements in real-time.

The goal is to ingest a massive stream of click events, aggregate them (e.g., "Clicks per minute per Ad"), and allow advertisers to view these statistics via a dashboard for performance monitoring and billing.

  • User Groups:
    • End Users: People clicking ads on websites or mobile apps.
    • Advertisers: Business owners querying the system to check campaign performance.
  • Main Actions:
    • Ingest: Receive the click, log it, and immediately redirect the user to the advertiser's landing page.
    • Process: Filter duplicate clicks and aggregate counts by time window.
    • Report: Provide an API for dashboards to query historical stats.
  • Scope:
    • In Scope: Ingestion API, Stream Processing, Data Storage, and Analytics API.
    • Out of Scope: Ad Serving (bidding/selecting ads), payment processing, and managing user profiles.
Image

2. Clarify functional requirements

Must Have:

  • Click Ingestion: An endpoint that accepts a click request and redirects the user to the target URL.

  • Real-time Aggregation: Clicks must be counted by Ad ID in fixed time windows (e.g., 1-minute intervals).

  • Deduplication (Idempotency): Prevent double-counting if a user clicks the same ad multiple times in quick succession.

  • Reporting API: An endpoint to retrieve the total click counts for a specific Ad and time range.

Nice to Have:

  • Late Event Handling: Gracefully handle clicks that arrive delayed due to network lag.

  • Fraud Detection: Basic filtering to reject clicks from known bot IP addresses.

Image

3. Clarify non-functional requirements

  • Scale: Support 1 Billion clicks per day.

  • Read vs. Write: Extremely Write Heavy (millions of clicks vs. occasional dashboard queries).

  • Latency:

    • Ingestion: Extremely low (< 20ms) to ensure the redirect happens instantly for the user.
    • Freshness: Aggregated stats should be available in the dashboard within 1 to 2 minutes.
  • Availability: High (99.99%). If the ingestion service is down, ad links are broken, and we lose revenue.

  • Accuracy: High. This data is used for billing. We aim for exactly-once processing or strong deduplication.

  • Retention: Raw logs for 30 days (audit); Aggregated stats for 2 years.

Image

4. Back of the envelope estimates

  • Traffic Calculation:
    • Total Clicks: 1 Billion / day.
    • Seconds in a day: ~86,400.
    • Average QPS: clicks/sec.
    • Peak QPS: Traffic is spiky. Assume 5x average = ~58,000 clicks/sec.
  • Storage Calculation (Raw):
    • Raw Event Size: ~0.5 KB (Headers, IP, User Agent, Ad ID, Timestamp).
    • Daily Raw Storage: 1B * 0.5 KB = 500 GB / day.
    • Monthly Raw Storage: ≈ 15 TB.
  • Storage Calculation (Aggregated):
    • We store 1 counter per minute per active ad. This is < 5% of raw storage size.
  • Bandwidth:
    • Ingress: 11,500 * 0.5 KB ≈ 5.8 MB/s. This is very manageable.
Image

5. API design

We need two main endpoints: one for the "write" path (tracking) and one for the "read" path (reporting).

1. Track Click (Ingestion)

  • Method: GET /v1/ads/click
    • Why GET? Ad clicks are usually navigation events. The browser requests this URL, and we respond with a 302 Redirect.
  • Query Params:
    • ad_id: Unique identifier for the ad.
    • redirect_url: Encoded URL of the target landing page.
    • timestamp: Client-side timestamp.
    • signature: HMAC signature to prevent tampering.
  • Response:
    • 302 Found: Header Location: <redirect_url>.

2. Get Ad Stats (Reporting)

  • Method: GET /v1/analytics/stats
  • Query Params:
    • ad_id: UUID of the ad.
    • start_ts: Epoch timestamp (inclusive).
    • end_ts: Epoch timestamp (exclusive).
    • granularity: 1min, 1hour, 1day.
  • Response:
{ "ad\_id": "ad\_123", "total\_clicks": 1500, "series": \[ {"ts": 1678900000, "count": 100}, {"ts": 1678900060, "count": 120} \] }

6. High level architecture

We will use a streaming architecture to decouple the fast "write" path from the slower "processing" path.

Components:

  1. Ingestion Service: A lightweight, stateless web server (Go/Node.js). It logs the click to Kafka and immediately returns the HTTP 302 Redirect. It does not write to the database.

  2. Message Queue (Kafka): Buffers the massive stream of clicks. Ensures we don't lose data if the database slows down and smoothes out traffic spikes.

  3. Stream Processor (Apache Flink): The core worker. It reads from Kafka, performs deduplication, and aggregates clicks into time windows (e.g., 1-minute buckets) in memory.

  4. OLAP/Time-Series Database (Cassandra): Stores the aggregated counters. Optimized for high write throughput.

  5. Raw Storage (S3): We use a "Kafka Connect" sink to dump raw events to S3 for auditing and backup.

  6. Analytics Service: Reads from the database to serve the dashboard API.

Image

7. Data model

We need two storage layers: one for the raw stream (backup) and one for aggregated views (serving).

1. Aggregated Data (Cassandra)

  • Why: Cassandra handles massive write loads efficiently and is good for time-series data.
  • Table: ad_stats_1min
    • ad_id (Partition Key): Groups all data for one ad on the same node for fast retrieval.
    • bucket_ts (Clustering Key): The minute timestamp (e.g., 10:00:00). Sorts data by time on disk.
    • click_count (Counter): The aggregated value.

2. Raw Data (S3 Data Lake)

  • Format: Parquet (compressed columnar).
  • Path: s3://logs/year=2023/month=10/day=27/...
  • Purpose: Source of truth. If our aggregation logic has a bug, we can fix the code and "replay" these logs to correct the numbers.

8. Core flows end to end

Here is a detailed breakdown of Section 8: Core Flows, expanded with technical depth on how these components interact to achieve the 20ms latency requirement and the massive scale of 1 billion clicks.

Flow 1: Click Ingestion (The Fast Path)

Goal: Log the event and get the user to their destination as fast as physically possible (< 20ms).

This flow is "latency-critical." If this is slow, the user stares at a white screen and closes the tab, costing the advertiser money.

  1. The User Action:
    The user is on a third-party site (e.g., a news blog) and clicks a banner ad. The URL is not the final destination; it is our tracking URL:
    https://api.ad-aggregator.com/v1/click?ad\_id=123\&redirect\_url=target.com\&sig=abc

  2. Load Balancing & Termination:
    The request hits a global Load Balancer (LB). The LB performs SSL termination (decrypting HTTPS) effectively here to offload CPU work from the application servers.

  3. The Ingestion Service (Stateless Worker):
    The request arrives at a Node.js or Go worker. This worker performs two actions in parallel:

    • Validation: It quickly checks the HMAC signature (sig) to ensure the request wasn't tampered with by a bot trying to inject fake clicks.
    • Event Production: It constructs a JSON payload containing the metadata (ad_id, timestamp, user_ip, user_agent).
  4. Async Write to Kafka:
    The service pushes this JSON payload to the raw_clicks Kafka topic.

    • Optimization: We use acks=1 (leader acknowledgement) or asynchronous sends. We do not wait for the message to be fully replicated to all Kafka brokers before responding to the user. Speed is prioritized over absolute durability here (rare data loss is acceptable, high latency is not).
  5. The Redirect:
    The service immediately responds with HTTP 302 Found.

    • Why 302 and not 301? A 301 redirect is "Permanent." Browsers cache 301s. If we sent a 301, the next time the user clicked the ad, the browser would skip our server entirely and go straight to the target, causing us to miss the tracking event.
Image

Flow 2: Stream Aggregation (The Processing Path)

Goal: Turn massive, noisy data streams into clean, compact metrics.

This is where the heavy lifting happens. We are converting a "Write Heavy" problem (11,500 events/sec) into a manageable "Write Light" problem for the database.

  1. Consumption (Partitioning Strategy):
    The Stream Processor (Apache Flink) connects to Kafka.

    • Keying: The data in Kafka is keyed by ad_id. This ensures that all clicks for "Nike Sneaker Ad" land on the same Kafka partition and are processed by the same Flink task slot. This eliminates the need for distributed locking.
  2. Tumbling Windows:
    Flink groups the incoming stream into "Tumbling Windows" of fixed time (e.g., 1 Minute).

    • Concept: A tumbling window means events from 12:00:00 to 12:00:59 are in Bucket A. Events from 12:01:00 start a fresh Bucket B. There is no overlap.
  3. Real-Time Deduplication (Idempotency):
    Within the memory of the Flink job, we maintain a temporary state structure (like a Bloom Filter or a HashSet) for the active window.

    • Logic: When a click comes in for Ad_123 from IP 1.2.3.4, the processor checks the set.
    • Hit: If 1.2.3.4 exists in the set, the click is a duplicate (user double-clicked). Discard event.
    • Miss: If not found, add 1.2.3.4 to the set and increment the counter.
  4. Aggregation & Flush:
    Instead of writing to the database 10,000 times, Flink holds the count in memory.

    • Map Reduce: 10,000 raw events → 1 integer variable in memory (Value: 10,000).
    • The Write: Once the 1-minute window closes, Flink executes a single CQL (Cassandra Query Language) command:
      UPDATE ad_stats SET clicks = clicks + 10000 WHERE ad_id = '123' AND ts = '12:00'
    • This reduces Database Ops (IOPS) by a factor of 100x to 1000x.
Image

Flow 3: Dashboard Read (The Analytics Path)

Goal: Retrieve historical data instantly for advertisers.

  1. The Request:
    An advertiser opens their dashboard to view performance for "Yesterday."
    Request: GET /stats?ad_id=123&start=1698000000&end=1698086400
  2. Service Layer Logic:
    The Analytics Service receives the request.
    • Check Cache: It first checks Redis. If the data for this exact time range exists, return it immediately.
    • Cache Miss: If not, query the database.
  3. Cassandra Query (Efficient Range Scan):
    The database schema is optimized for this specific query.
    • Partition Key (ad_id): Cassandra hashes "123" and knows exactly which node holds this data. No broadcasting to all nodes.
    • Clustering Key (bucket_ts): On that specific node, the data is stored sorted by time on the disk.
    • Retrieval: Cassandra seeks to the start timestamp and sequentially reads the rows until the end timestamp. This avoids random I/O seek time, making the read extremely fast.
  4. Transformation:
    The Analytics Service gets back 1,440 rows (minutes in a day). It formats this into a JSON array for the frontend charting library (e.g., Recharts or D3.js) and returns the response.
Image

9. Caching and read performance

  • Ingestion Path: No caching. Speed comes from async Kafka writes.

  • Read Path (Dashboard):

    • Cache: Redis.
    • Hot Data (Today): Cache the query result with a short TTL (e.g., 30 seconds). Advertisers refreshing the page frequently won't hit the DB every time.
    • Cold Data (Yesterday): Cache with a long TTL (24 hours). Historical data is immutable.
    • Key Strategy: stats:{ad_id}:{start_ts}:{end_ts}.

10. Storage, indexing and media

  • Primary Storage (Cassandra):
    • Indexing: The Primary Key (ad_id, bucket_ts) acts as the index. It allows O(1) lookup for an Ad and efficient range scans for time.
    • TTL: We can set a Time-To-Live on rows (e.g., 2 years) to automatically delete old data and save costs.
  • Media Storage:
    • Ad images and videos are not stored here. They are stored in Object Storage (S3) and served via a CDN (like CloudFront) by the Ad Server. We only track the metadata (IDs).

11. Scaling strategies

  • Kafka Partitioning:
    • We partition the raw_clicks topic by ad_id. This ensures all clicks for "Ad 123" go to the same consumer instance, making memory-based aggregation safe and easy.
  • Handling "Hot Spots" (The Super Bowl Problem):
    • Risk: If Ad X gets 1 million clicks/sec, Partition X and Consumer X will crash.
    • Solution (Scatter-Gather):
      1. Ingestion: Partition Kafka by random or user_ip instead of ad_id during the peak.
      2. Aggregation: Flink consumers aggregate partial counts locally.
      3. Finalize: A second Flink stage (or the DB) sums the partial counts to get the global total.
  • Database Sharding:
    • Cassandra shards by ad_id automatically. We can scale out by adding more nodes.

12. Reliability, failure handling and backpressure

  • Data Accuracy (Billing):
    • Lambda Architecture: The stream processor gives us "fast" numbers. To ensure 100% accuracy for billing, we run a nightly Spark Job on the raw S3 logs to re-calculate the exact counts and overwrite the Cassandra entries. This corrects any data lost during streaming glitches.
  • Backpressure:
    • If the DB slows down, Flink stops reading from Kafka.
    • Kafka acts as a giant buffer (disk-based).
    • The Ingestion Service is unaffected; it keeps accepting users and pushing to Kafka.
  • Dead Letter Queue (DLQ):
    • Bad messages (e.g., corrupt JSON) are routed to a separate Kafka topic ("dead-letters") so they don't block the pipeline.

13. Security, privacy and abuse

  • Click Fraud:
    • Simple: Rate limiting (e.g., max 10 clicks/IP/hour) in the ingestion layer.
    • Advanced: The Aggregator drops clicks if the pattern looks robotic (e.g., exact 1.0s intervals).
  • Link Integrity:
    • The redirect_url should be signed with an HMAC secret. If the signature is invalid, we return 403. This prevents attackers from using our redirector for phishing.
  • Privacy:
    • We store IP addresses. To comply with GDPR, we should hash or mask the last octet (e.g., 192.168.1.xxx) before writing to S3.

14. Bottlenecks and next steps

  • Bottleneck: High Cardinality Aggregation.
    • If advertisers want to break down stats by City + OS + Browser + Ad, the number of combinations is too large for simple Cassandra counters.
    • Next Step: Migrate the reporting layer to a dedicated OLAP engine like ClickHouse or Apache Druid. These are designed to ingest raw streams and aggregate on-the-fly at query time.
  • Bottleneck: Global Latency.
    • If servers are only in the US, redirects will be slow for users in Asia.
    • Next Step: Deploy Ingestion Services in multiple regions (Edge Locations) that forward data to the central Kafka cluster.

Summary

  1. Architecture: Decoupled Ingestion (Kafka) vs. Processing (Flink) ensures user redirects are instant (<20ms).

  2. Efficiency: In-memory windowing reduces DB write pressure by ~100x.

  3. Scale: Partitioning by Ad ID allows linear scaling to billions of clicks.

  4. Accuracy: A "Lambda" approach (Real-time Stream + Nightly Batch) ensures billing data is 100% accurate.

Design Google Docs
Design a Live Comment Streaming Service (Twitch Chat)
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow 1: Click Ingestion (The Fast Path)

Flow 2: Stream Aggregation (The Processing Path)

Flow 3: Dashboard Read (The Analytics Path)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary